<template>
  <div class="staffSelector" v-if="isShow">
    <!-- <el-button
      v-if="showBtnTest"
      plain
      type="single-number"
      @click="showDialogInventory()"
    >
      {{ btnText }}
    </el-button> -->
    <el-dialog
      v-if="isShow"
      :title="title"
      :visible.sync="isShow"
      :mode="mode"
      width="900px"
      :before-close="closeDialog"
      append-to-body
    >
      <div class="left-trrr">
        <el-autocomplete
          clearable
          style="width: 360px; margin: 0 0 10px 20px"
          popper-class="tree-table-autocomplete"
          prefix-icon="el-icon-search"
          class="inline-input"
          v-model="seachData"
          placeholder="定位查找"
          @select="handleSelect"
          :fetch-suggestions="querySearch"
          :scrollBottom="handleScrollBottom"
        >
          <!-- :fetch-suggestions="querySearchAsync" -->
          <template slot-scope="{ item }">
            <div :title="item.name" class="org-name">
              <i :class="setSelectedIcon(item)" class="org-icon"></i>
              <span>{{ item.name }}</span>
            </div>
            <p class="org-full-name" :title="item.fullName">
              {{ item.fullName }}
            </p>
          </template>
        </el-autocomplete>
        <div class="tree-box">
          <el-tree
            :showLine="showLine"
            :load="loadNode"
            :props="props"
            :node-key="nodeKey"
            :default-expanded-keys="expandedKeys"
            lazy
            @node-click="handleNodeClick"
            @node-expand="showChildNode"
          >
            <!-- :render-content="renderContent" -->
            <span class="custom-tree-node" slot-scope="{ node }">
              <span>
                <i
                  class="icon-ccui-unit"
                  style="color: #0089ef"
                  v-if="node.data.orgType === '1'"
                ></i>
                <i
                  class="icon-ccui-organization"
                  style="color: #0089ef"
                  v-else
                ></i>
                {{ node.label }}
              </span>
            </span>
          </el-tree>
        </div>
      </div>

      <div class="selected">
        <p class="selected-count">{{ selectedTitle }}({{ selected.length }})</p>
        <ul class="selected-ul">
          <template v-for="(item, index) in selected">
            <li class="selected-li" :key="index">
              <i
                style="margin-right: 5px"
                :style="{ color: selectedIconColor }"
                :class="setSelectedIcon(item)"
                @click="removeArray(selected, item)"
              ></i>
              <span class="selected-name">{{ item.name }}</span>
              <i
                class="el-icon-close mt"
                v-if="mode === 'checkbox'"
                @click="removeArray(selected, item)"
              ></i>
            </li>
          </template>
        </ul>
      </div>

      <div size="mini" type="default-mini" slot="footer" class="dialog-footer">
        <el-button size="mini" type="default-mini" @click="closeDialog"
          >取消</el-button
        >
        <el-button size="mini" type="primary-font-mini" @click="confirmForm"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "staffSelector",
  props: {
    showBtnTest: {
      type: Boolean,
      default: true
    },
    btnText: {
      type: String,
      default: "新增"
    },
    selectedTitle: {
      type: String,
      default: "已选成员"
    },
    title: {
      type: String,
      default: "添加成员"
    },

    showLine: {
      type: Boolean,
      defualt: false
    },
    nodeKey: {
      type: String,
      default: "partyId"
    },
    props: {
      type: Object,
      default: () => {
        return {
          label: "name",
          children: "child1",
          isLeaf: "isLeaf"
        };
      }
    },

    requestTreeFunction: {
      type: Function,
      default: Function
    },
    requestTreeParams: {
      type: Object,
      default: function () {
        return {
          isPrincipal: 1,
          parentId: "", // 全局 其他【此组件是本级及以下】
          flag: "0", // 0 公司 1 部门 2 成员
          isCompany: "1" // 是否公司 0否 1是
        };
      }
    },
    requestTreeParamConfig: {
      //接口请求映射表
      type: Object,
      default: function () {
        return { parentId: "parentId" };
      }
    },

    requestSeachFunction: {
      type: Function,
      default: Function
    },
    requestSeachParams: {
      type: Object,
      default: function () {
        return {
          flag: 3,
          branchName: "",
          orgId: ""
        };
      }
    },
    requestSeachContent: {
      type: String,
      default: "branchName"
    },

    requestResultDataConfig: {
      type: String,
      default: "data"
    },
    selectlevel: {
      type: Number,
      default: 3
    },

    selectedIconColor: {
      type: String,
      default: "#0089ef"
    },
    selectedData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isselectedData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    mode: {
      validator: value => {
        return ["checkbox", "radio"].includes(value);
      },
      default: "checkbox"
    }
  },
  data() {
    return {
      seachData: "",
      isShow: false,
      expandedKeys: [],
      treeData: [],
      selected: [],
      firstCode: "",
      selectedCode: [],
      renderParams: {},
      resolve: Function,
      ishowTree: true,
      expandedlog: {},
      expandArr: []
    };
  },
  watch: {
    isShow(arr) {
      this.renderParams = this.requestTreeParams;
      this.selectedCode = [];
      this.expandArr = [];
      this.expandedKeys = [];
      // this.selected = [];
      const res = new Map();
      this.selected = this.isselectedData.filter(
        a => !res.has(a.name) && res.set(a.name, 1)
      ); //编辑的时候，原来本身有的部门，再选的时候会重复，所以要去重
    }
  },
  mounted() {},
  methods: {
    setSelectedIcon(val) {
      // console.log(">>>>>>>>", val, "<<<<<<<<");
      // if (sex === "2") {
      //   return "icon-ccui-organization is-leaf-org";
      // } else {
      //   return "icon-ccui-organization is-leaf-org";
      // }
      let arr = [
        "icon-ccui-organization",
        "icon-ccui-unit",
        "icon-ccui-man-hollow",
        "icon-ccui-woman-hollow"
      ];
      let keyClass = "";
      keyClass = arr[0];
      return keyClass;
    },
    setTreeICon(h, node, data, store) {
      //  console.log(node,data,store)
      if (data.orgType === "2") {
        if (data.sex === "2") {
          return <i class="icon-ccui-woman-hollow is-leaf-org"></i>;
        } else if (data.sex === "1") {
          return <i class="icon-ccui-man-hollow is-leaf-org"></i>;
        } else {
          return <i class="icon-ccui-man-hollow is-leaf-org"></i>;
        }
      }
      if (!data.orgType) {
        return <i class="icon-ccui-organization is-leaf-org"></i>;
      }
      if (data.orgType === "0") {
        return <i class="icon-ccui-organization is-leaf-org"></i>;
      }
      if (data.orgType === "1") {
        return <i class="icon-ccui-unit is-leaf-org"></i>;
      }
    },
    showDialogInventory() {
      this.isShow = true;
      this.$emit("update:isShow", true);
    },
    handleScrollBottom(data, callback) {
      let params = this.requestSeachParams;
      params[this.requestSeachContent] = this.seachData;
      params.pageNo++;
      this.requestSeachFunction(params).then(res => {
        let dataRows = res.data.data.rows;
        if (dataRows.length !== 0) {
          params.pageNo++;
          callback(dataRows);
        }
      });
    },
    handleSelect(seachItem) {
      if (this.mode === "radio") {
        this.selectedCode = [seachItem.autoCode];
        this.selected = [];
      } else {
        this.selectedCode.includes(seachItem.autoCode) ||
          this.selectedCode.push(seachItem.autoCode);
      }
      this.formatSelectedData(this.selectedCode);
      this.setIsSelected(this.expandArr);
    },

    querySearch(queryString, cb) {
      this.seachData = queryString;
      let params = this.requestSeachParams;
      params[this.requestSeachContent] = queryString;
      params.pageNo = 1;
      this.requestSeachFunction(params)
        .then(res => {
          cb(res.data.data.rows);
          // params.pageNo++;
        })
        .catch(e => {});
    },

    formatSelectedData(arr) {
      if (arr.length < 0) {
        return false;
      }
      let firstCode = this.firstCode + "";
      arr.forEach(item => {
        let codeItem = item.split("-");
        let index = codeItem.indexOf(firstCode);
        let newcodeArr = codeItem.slice(index);
        let [lastItem] = newcodeArr.slice(-1);
        if (lastItem === "") {
          newcodeArr = newcodeArr.slice(0, -2);
        }
        newcodeArr.forEach(code => {
          if (!this.expandedKeys.includes(code)) {
            this.expandedKeys.push(code);
          }
        });
      });
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        this.requestTreeFunction(this.renderParams).then(res => {
          this.treeData = res.data[this.requestResultDataConfig];
          if (!this.treeData[0].parentId) {
            this.treeData[0].parentId = this.treeData[0].partyId;
          }
          this.firstCode =
            this.treeData[0].parentId !== "" && this.treeData[0].parentId;
          if (this.selectedCode.length > 0) {
            this.formatSelectedData(this.selectedCode);
          } else {
            this.treeData.forEach(item => {
              this.expandedKeys.push(item.parentId);
            });
          }
          this.treeData.forEach(item => {
            this.expandedKeys.push(item.parentId);
          });
          this.expandArr.push(...this.treeData);
          resolve(this.treeData);
        });
      }

      if (node.level > 0) {
        let cloneParams = Object.assign({}, this.renderParams);
        cloneParams.parentId = node.data.partyId;
        this.requestTreeFunction(cloneParams).then(res => {
          let resolveData = res.data.data[0].child;
          this.setIsSelected(resolveData);
          this.expandArr.push(...resolveData);
          resolve(resolveData);
        });
      }
    },

    closeDialog() {
      this.isShow = false;
      this.$emit("update:isShow", false);
    },

    confirmForm() {
      // alert(JSON.stringify(this.selected));
      this.$emit("selectedStaffSuccess", this.selected);
      this.closeDialog();
    },
    renderContent(h, { node, data, store }) {
      let isSelectedHtml;
      if (data.isSelected) {
        isSelectedHtml = (
          <i class="el-icon-check" style="margin-right:15px"></i>
        );
      }

      return (
        <span style="flex: 1; display: flex; align-items: center; justify-content: space-between; font-size: 14px; padding-right: 8px;">
          <span>
            {this.setTreeICon(h, node, data, store)}
            <span>{node.label}</span>
          </span>
          <span>{isSelectedHtml}</span>
        </span>
      );
    },
    showChildNode(data, node) {},

    handleNodeClick(data, node, tree) {
      if (data) {
        if (this.mode === "radio") {
          this.selected.forEach(item => (item.isSelected = false));
          this.selected = [data];
          data.isSelected = true;
        } else {
          if (!data.isSelected) {
            data.isSelected = true;
            this.selected.push(data);
            this.selectedCode.push(data.autoCode);
          } else {
            this.removeArray(this.selected, data);
          }
        }
      }
    },
    setIsSelected(arr) {
      arr.map(item => {
        if (this.selectedCode.includes(item.autoCode)) {
          item.isSelected = true;
          let reslut = this.selected.some(({ autoCode }, i, thisarr) => {
            if (autoCode === item.autoCode) {
              thisarr.splice(i, 1, item);
              return true;
            }
          });
          reslut || this.selected.push(item);
        } else {
          item.isSelected = false;
        }
      });
    },
    removeArray(arr, delItem) {
      let condeIndex = this.selectedCode.indexOf(delItem.autoCode);
      this.selectedCode.splice(condeIndex, 1);
      delItem.isSelected = false;
      let index = arr.indexOf(delItem);
      arr.splice(index, 1);
    }
  }
};
</script>

<style lang="scss" scoped>
.staffSelector {
  display: inline-block;
}
ul,
li {
  margin: 0;
  padding: 0;
  list-style: none;
}
.selected-name {
  color: #4a4a4a;
}
.el-icon-close {
  float: right;
  cursor: pointer;
}
.selected-li {
  line-height: 18px;
  margin: 10px auto;
}
/deep/ .el-dialog__body {
  padding: 20px;
}

.el-tree >>> .is-leaf-org {
  padding-left: -10px;
  padding-right: 6px;
  color: #0089ef;
}

.custom-tree-node {
  width: 106px;
  height: 18px;
  font-size: 13px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: rgba(74, 74, 74, 1);
  line-height: 18px;
}

.left-trrr {
  width: 450px;
  float: left;
  border: 1px solid #f1f1f1;
  padding-top: 10px;
}
.tree-box {
  height: calc(100vh - 360px);
  overflow: auto;
  padding: 0 12px;
}
.selected {
  float: right;
  border: 1px solid #f1f1f1;
  width: 380px;
}

.selected-count {
  color: #4a4a4a;
  font-size: 14px;
  padding: 10px 20px;
  border-bottom: 1px solid #f1f1f1;
  margin-bottom: 16px;
}
.selected-ul li {
  font-size: 14px;
  margin: 0;
  padding: 0 20px 12px 20px;
}
.selected-ul li:first-child {
  margin-top: 3px;
}
.mt {
  margin-top: 2px;
}
.selected-ul {
  height: calc(100vh - 366px);
  overflow: auto;
}
.org-name {
  line-height: 18px;
}
.org-name span {
  font-size: 13px;
  color: #4a4a4a;
}
.org-full-name {
  line-height: 18px;
  margin-top: 5px;
  font-size: 13px;
  color: #999999;
  margin-left: 17px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.org-icon {
  color: #0089ef;
  margin-right: 5px;
}
// /deep/ .el-input__suffix {
//   right: -190px;
// }
</style>
